package com.piece.spider.controller;

import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.mongo.entity.MongoJobLog;
import com.piece.core.mongo.service.MongoJobLogService;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.file.FileUtil;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.module.spider.concurrent.SpiderJob;
import com.piece.module.spider.context.SpiderContext;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.io.File;

@RefreshScope
@RestController
@Api(tags = {"爬虫通知管理"})
@RequestMapping(value = "/api/spider/task")
public class SpiderTaskController extends FrameWorkController {

    @Value("${spider.workspace:#{null}}")
    private String workspace;

    @Resource
    private MongoJobLogService mongoJobLogService;

    @RequestMapping(value = "/table")
    @AclPermission(code = "spider:program:view")
    @ApiOperation(value = "获取爬虫任务分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable<MongoJobLog> dataTable = mongoJobLogService.findPage(queryTable);
        return success(dataTable);
    }

    @SubmitPermission
    @PostMapping("/delete/{id}")
    @AclPermission(code = "spider:program:delete")
    @ApiOperation(value = "删除爬虫任务")
    @ApiImplicitParam(name = "id", value = "任务ID", type = "path")
    public AjaxResponse delete(@PathVariable String id) {
        try {
            // 删除任务记录之前先停止
            SpiderContext context = SpiderJob.getSpiderContext(id);
            if (null != context) {
                context.setRunning(false);
            }
            MongoJobLog jobLog = mongoJobLogService.findOne(id);
            if (null != jobLog) {
                String path = FileUtil.getStoragePath(workspace);
                // 删除日志文件
                File logFile = new File(path, jobLog.getJobGroup() + File.separator + "logs" + File.separator + id + ".log");
                if (logFile.exists()) {
                    logFile.delete();
                }
            }
            mongoJobLogService.delete(id);
            return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS));
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.DELETE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/stop/{id}")
    @AclPermission(code = "spider:program:edit")
    @ApiOperation(value = "停止爬虫任务")
    @ApiImplicitParam(name = "id", value = "任务ID", type = "path")
    public AjaxResponse stop(@PathVariable String id) {
        try {
            SpiderContext context = SpiderJob.getSpiderContext(id);
            if (null != context) {
                context.setRunning(false);
            }
            return success(I18nUtil.message(ExceptionConstants.MESSAGE_SUCCESS));
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.MESSAGE_ERROR), e.getMessage());
        }
    }
}
